package com.serverdemo.core.net;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 消息解码
 * Created by wangqiang on 2020/4/9.
 */
public class Decoder extends ByteToMessageDecoder
{
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception
    {
        int bufLength = byteBuf.readableBytes();

        if (bufLength < NetConstant.PACKET_HEADER_LENGTH)
        {
            return;
        }

        byteBuf.markReaderIndex();

        int packetID = byteBuf.readInt();
        int packetBodyLength = byteBuf.readInt();

        if (packetID < 0 || packetBodyLength <= 0 || packetBodyLength >= NetConstant.PACKET_MAX_LENGTH)
        {
            throw new IllegalStateException("packet length invalid");
        }

        // 不够一个包长度,继续接收
        if (byteBuf.readableBytes() < packetBodyLength)
        {
            byteBuf.resetReaderIndex();
            return;
        }

        NetPacket netPacket = new NetPacket();
        netPacket.setId(packetID);
        netPacket.setLength(packetBodyLength);
        byte body[] = new byte[packetBodyLength];
        byteBuf.readBytes(body);
        netPacket.setBody(body);

        list.add(netPacket);
    }
}
